/*
 * @Author: kevin.huang 
 * @Date: 2018-07-21 19:48:42 
 * @Last Modified by: kevin.huang
 * @Last Modified time: 2019-03-24 19:24:42
 * Copyright (c): kevin.huang Released under MIT License
 */
(function (global, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['$B'], function (_$B) {
            return  factory(global, _$B);
        });
    } else {
        if(!global["$B"]){
            global["$B"] = {};
        }
        factory(global, global["$B"]);
    }
}(typeof window !== "undefined" ? window : this, function (window, $B) {
    var def = {
        pageSize: 15, //页大小
        height: 25,
        pageList: [15,20,25,30,35,40,55,70,80,90,100], //页大小项
        page: 1, //当前页
        startpg: 1, //开始页
        buttons: 5, //页按钮数量
        position: 'right', // right center left
        summary: true //是否需要页大小，页总数汇总显示
    };

    function _create() {
        var last, next, prev, first;
        var nubWrap = $("<div style='float:left;' class='k_pagination_num_wrap k_box_size'></div>");
        var opts = this.opts;

        function click(e) {
            var $t = $(this);
            var flag = $t.data("pg");
            var curActived;
            if ($t.hasClass("k_pagination_disabled")) {
                return;
            }
            if (flag === "r") { //刷新
                var isTrigger = $t.data("isTrigger");
                if (isTrigger) {
                    createNum(opts.startpg);
                    createSum();
                } else {
                    setTimeout(function () {
                        opts.onClick(opts.page, opts.pageSize, opts.startpg);
                    }, 10);
                }
            } else if (flag === 1) { //第一页
                opts.startpg = 1;
                opts.page = 1;
                createNum(opts.startpg);
                setTimeout(function () {
                    opts.onClick(opts.page, opts.pageSize, opts.startpg);
                }, 10);
            } else if (flag === "mn") { //向前翻
                opts.startpg = opts.startpg + opts.buttons;
                if (opts.startpg <= 0) {
                    opts.startpg = 1;
                }
                opts.page = opts.startpg;
                createNum(opts.startpg);
                setTimeout(function () {
                    opts.onClick(opts.page, opts.pageSize, opts.startpg);
                }, 10);
            } else if (flag === "mp") { //向后翻
                opts.startpg = opts.startpg - opts.buttons;
                if (opts.startpg <= 0) {
                    opts.startpg = 1;
                }
                opts.page = opts.startpg;
                createNum(opts.startpg);
                setTimeout(function () {
                    opts.onClick(opts.page, opts.pageSize, opts.startpg);
                }, 10);
            } else if (flag === "l") { //最后一页            	
                opts.startpg = opts.pageCount - opts.buttons + 1;
                if (opts.startpg <= 0) {
                    opts.startpg = 1;
                }
                opts.page = opts.pageCount;
                createNum(opts.startpg);
                setTimeout(function () {
                    opts.onClick(opts.page, opts.pageSize, opts.startpg);
                }, 10);
            } else if (flag === 'p') { //前一页
                curActived = nubWrap.children(".actived").removeClass("actived");
                var activedPrev = curActived.prev();
                if (activedPrev.length > 0) {
                    opts.page = activedPrev.addClass("actived").data("pg");
                    if (opts.page === 1) {
                        first.addClass("k_pagination_disabled");
                        prev.addClass("k_pagination_disabled");
                    }
                } else {
                    opts.page = curActived.data("pg") - 1;
                    if (opts.page < 1) {
                        opts.page = 1;
                    }
                    opts.startpg = opts.page - opts.buttons + 1;
                    createNum(opts.startpg);
                }
                setTimeout(function () {
                    opts.onClick(opts.page, opts.pageSize, opts.startpg);
                }, 2);
            } else if (flag === 'n') { //下一页
                curActived = nubWrap.children(".actived").removeClass("actived");
                var activedNext = curActived.next();
                if (activedNext.length > 0) {
                    opts.page = activedNext.addClass("actived").data("pg");
                    if (opts.page === opts.pageCount) {
                        last.addClass("k_pagination_disabled");
                        next.addClass("k_pagination_disabled");
                    }
                } else {
                    opts.page = curActived.data("pg") + 1;
                    opts.startpg = opts.page;
                    createNum(opts.startpg);
                }
                setTimeout(function () {
                    opts.onClick(opts.page, opts.pageSize, opts.startpg);
                }, 10);
            }
            return false;
        }

        opts.pageCount = Math.ceil(opts.total / opts.pageSize) || 1; //总页数
        var wrap = this.jqObj.children();
        wrap.children().remove();
        var h = wrap.height();
        var fresh = $("<a style='line-height:" + h + "px;height:" + h + "px' class='k_pagination_fresh k_box_size'><i style='line-height:" + h + "px' class='fa fa-refresh'></i><div class='a_div'></div></a>").appendTo(wrap);
        fresh.click(click).data("pg", "r").hide();
        first = $("<a style='line-height:" + h + "px;height:" + h + "px' class='k_pagination_first k_box_size'><i style='line-height:" + h + "px' class='fa fa-angle-double-left'></i><div class='a_div'></div></a>").appendTo(wrap);
        first.children("i").removeAttr("class").text($B.config.firstPage);
        first.hide();
        first.click(click).data("pg", 1);
        prev = $("<a style='line-height:" + h + "px;height:" + h + "px' class='k_pagination_prev k_box_size'><i style='line-height:" + h + "px' class='fa fa-angle-left'></i><div class='a_div'></div></a>").appendTo(wrap);
        prev.children("i").removeAttr("class").text($B.config.prevPage);
        prev.click(click).data("pg", "p");
        if (opts.page === 1) {
            first.addClass("k_pagination_disabled");
            prev.addClass("k_pagination_disabled");
        }
        nubWrap.insertAfter(prev);

        function createNum(_st) {
            if (_st < 1) {
                _st = 1;
            }

            nubWrap.children().remove();
            wrap.children(".k_pagination_more").remove();
            if (_st !== 1 && _st !== opts.startpg) {
                $("<a style='line-height:" + h + "px;height:" + h + "px' class='k_pagination_more k_box_size'>...<div class='a_div'></div></a>").insertBefore(nubWrap).click(click).data("pg", "mp");
                first.removeClass("k_pagination_disabled");
                prev.removeClass("k_pagination_disabled");
            } else {
                first.addClass("k_pagination_disabled");
                prev.addClass("k_pagination_disabled");
            }
            if (last) {
                if (_st + opts.buttons >= opts.pageCount) {
                    last.addClass("k_pagination_disabled");
                    if (opts.page === opts.pageCount) {
                        next.addClass("k_pagination_disabled");
                    }
                } else {
                    last.removeClass("k_pagination_disabled");
                    next.removeClass("k_pagination_disabled");
                }
            }
            var help = opts.buttons;
            var aClickFn = function () {
                var $t = $(this);
                opts.page = $t.addClass("actived").data("pg");
                $t.siblings().removeClass("actived");
                if (opts.page === 1) {
                    first.addClass("k_pagination_disabled");
                    prev.addClass("k_pagination_disabled");
                } else {
                    first.removeClass("k_pagination_disabled");
                    prev.removeClass("k_pagination_disabled");
                }
                if (opts.page === opts.pageCount) {
                    last.addClass("k_pagination_disabled");
                    next.addClass("k_pagination_disabled");
                } else {
                    last.removeClass("k_pagination_disabled");
                    next.removeClass("k_pagination_disabled");
                }
                setTimeout(function () {
                    opts.onClick(opts.page, opts.pageSize, opts.startpg);
                }, 10);
            };
            while (help > 0 && _st <= opts.pageCount) {
                var $a = $("<a style='line-height:" + h + "px;height:" + h + "px' class='k_box_size k_pg_number'>" + _st + "<div class='a_div'></div></a>").appendTo(nubWrap).data("pg", _st);
                if (_st === opts.page) {
                    $a.addClass("actived");
                }
                $a.click(aClickFn);
                _st++;
                help--;
            }
            if (_st < opts.pageCount) {
                var $tmp = $("<a style='line-height:" + h + "px;height:" + h + "px' class='k_pagination_more k_box_size'>...<div class='a_div'></div></a>").insertAfter(nubWrap).click(click).data("pg", "mn");
            }
            if (opts.position === "center") {
                var w = 0;
                wrap.children().each(function () {
                    var $t = $(this);
                    w = w + $t.outerWidth() + 3;
                });
                wrap.width(w);
            }
        }
        createNum(opts.startpg);
        next = $("<a style='line-height:" + h + "px;height:" + h + "px' class='k_pagination_prev k_box_size'><i style='line-height:" + h + "px' class='fa fa-angle-right'></i><div class='a_div'></div></a>").appendTo(wrap).data("pg", "n");
        next.click(click);
        next.children("i").removeAttr("class").text($B.config.nextPage);
        if (opts.pageCount === 1) {
            next.addClass("k_pagination_disabled");
        }
        var lastBtn = $("<a style='line-height:" + h + "px;height:" + h + "px' class='k_pagination_last k_box_size'><i style='line-height:" + h + "px' class='fa fa-angle-double-right'></i><div class='a_div'></div></a>").appendTo(wrap).data("pg", "l");
        lastBtn.click(click);
        lastBtn.children("i").removeAttr("class").text($B.config.lastPage);
        last = lastBtn.hide();
        if (opts.startpg < opts.pageCount) {
            lastBtn.removeClass("k_pagination_disabled");
        } else {
            lastBtn.addClass("k_pagination_disabled");
        }
        var $sp = $("<span class='k_pagination_input_wrap'>" + $B.config.go2page + "&nbsp<input type='text'/>&nbsp" + $B.config.go2pageSuffix + "&nbsp<button class='k_pagination_input_button'>" + $B.config.buttonOkText + "</button></span>").appendTo(wrap);
        $sp.children("button").click(function () {
            var $t = $(this);
            var opts = $t.data("opts");
            var v = $t.siblings("input").val();
            if (v !== "") {
                try {
                    opts.startpg = parseInt(v);
                    if (opts.startpg > opts.pageCount || opts.startpg < 1) {
                        opts.startpg = 1;
                    }
                    opts.page = opts.startpg;
                    opts.onClick(opts.page, opts.pageSize, opts.startpg);
                } catch (e) { }
            }
        }).data("opts", opts);

        function compare(val1, val2) {
            if(val1 < val2) {
              return -1;
            } else if(val1 > val2) {
              return 1;
            } else {
              return 0;
            }
        }

        function createSum() {
            if (!opts.summary) {
                return;
            }
            wrap.children(".k_pagination_sum").remove();
            //"+opts.pageCount+"页
            var arr = ["<div class='k_pagination_sum'>" + $B.config.pageSum.replace("{total}", opts.total) + "<select>"];
            var pageList = opts.pageList.slice(0,opts.pageList.length);
            pageList.push(opts.pageSize);           
           /* opts.pageList.push(opts.pageSize);*/
            pageList = pageList.unique();
            pageList.sort(compare);          
            for (var i = 0, l = pageList.length; i < l; ++i) {
                var _tmp = "";
                if (pageList[i] === opts.pageSize) {
                    _tmp = "selected=selected";
                }
                arr.push("<option " + _tmp + " value='" + pageList[i] + "'>" + pageList[i] + "</option>");
            }
            arr.push("</select>" + $B.config.pageSumSuffix + "</div>");
            $(arr.join("")).prependTo(wrap).children("select").change(function () {
                var psize = parseInt($(this).val());
                opts.pageSize = psize;
                setTimeout(function () {
                    opts.onClick(1, opts.pageSize, 1);
                }, 10);
            });
        }
        createSum();
        if (opts.position === "center") {
            var w = 0;
            wrap.children().each(function () {
                var $t = $(this);
                w = w + $t.outerWidth() + 3;
            });
            wrap.width(w);
        }
        this.first = first;
        this.last = lastBtn;
        this.next = next;
        this.prev = prev;
        //根据当前页设置 按钮样式
        //最后一页
        if (opts.page === opts.pageCount) {
            if (opts.page > 1) {
                this.first.removeClass("k_pagination_disabled");
                this.prev.removeClass("k_pagination_disabled");
                this.last.addClass("k_pagination_disabled");
                this.next.addClass("k_pagination_disabled");
            } else {
                this.first.addClass("k_pagination_disabled");
                this.prev.addClass("k_pagination_disabled");
                this.last.addClass("k_pagination_disabled");
                this.next.addClass("k_pagination_disabled");
            }
        } else if (opts.page === 1) { //第一页
            if (opts.page < opts.pageCount) {
                this.first.addClass("k_pagination_disabled");
                this.prev.addClass("k_pagination_disabled");
                this.last.removeClass("k_pagination_disabled");
                this.next.removeClass("k_pagination_disabled");
            } else {
                this.first.addClass("k_pagination_disabled");
                this.prev.addClass("k_pagination_disabled");
                this.last.addClass("k_pagination_disabled");
                this.next.addClass("k_pagination_disabled");
            }
        } else {
            this.first.removeClass("k_pagination_disabled");
            this.prev.removeClass("k_pagination_disabled");
            this.last.removeClass("k_pagination_disabled");
            this.next.removeClass("k_pagination_disabled");
        }
    }

    function Pagination(jqObj, opts) {
        $B.extend(this, Pagination);
        this.opts = $.extend({}, def, opts);
        this.jqObj = jqObj.addClass("k_pagination_wrap clearfix");
        this.jqObj.append("<div class='k_pagination_" + this.opts.position + "'></div>");
        if (opts.height) {
            var lineHeight = opts.height + "";
            if(lineHeight.indexOf("px") < 0){
                lineHeight = lineHeight + "px";
            }
            this.jqObj.height(opts.height).css("line-height" ,lineHeight );
        }
        _create.call(this);
    }
    Pagination.prototype = {
        constructor: Pagination,
        /***新分页工具栏
        *args={
            total:1,//总数量
         }
        ***/
        update: function (args) {
            this.opts.page = 1;
            this.opts.startpg = 1;
            $.extend(this.opts, args);
            this.opts.pageCount = Math.ceil(this.opts.total / this.opts.pageSize) || 1; //总页数
            if (this.opts.startpg >= this.opts.pageCount) {
                this.opts.startpg = 1;
            }
            var $re = this.jqObj.children().children(".k_pagination_fresh").data("isTrigger", true);
            $re.trigger("click");
            $re.data("isTrigger", false);
            if (this.opts.page !== 1) {
                this.first.removeClass("k_pagination_disabled");
                this.prev.removeClass("k_pagination_disabled");
            } else {
                this.first.addClass("k_pagination_disabled");
                this.prev.addClass("k_pagination_disabled");
            }
            if (this.opts.page === this.opts.pageCount) {
                this.last.addClass("k_pagination_disabled");
                this.next.addClass("k_pagination_disabled");
            } else {
                this.last.removeClass("k_pagination_disabled");
                this.next.removeClass("k_pagination_disabled");
            }
        },
        /**
         *获取当前页
         ****/
        getCurPage: function () {
            return this.opts.page;
        }
    };
    $B["Pagination"] = Pagination;
    return Pagination;
}));